

//
//  NetworkTool.swift
//  Soap协议XML解析
//
//  Created by xuNick on 16/7/17.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit

import AFNetworking

import SVProgressHUD

import AEXML

//typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
//    AFNetworkReachabilityStatusUnknown          = -1,
//    AFNetworkReachabilityStatusNotReachable     = 0,
//    AFNetworkReachabilityStatusReachableViaWWAN = 1,
//    AFNetworkReachabilityStatusReachableViaWiFi = 2,
//};


class NetworkTool: AFHTTPSessionManager {
    
     //MARK: - 全局访问点
    static let sharedTools: NetworkTool = {
        
        let tools = NetworkTool()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/xml")
        tools.responseSerializer = AFHTTPResponseSerializer()
        let manager = AFNetworkReachabilityManager.shared()
        manager.setReachabilityStatusChange({ (Status) in
            switch Status{
            case .unknown:
                print("位置网络=================")
                break
            case .notReachable:
                print("无连接=================")
                break
            case .reachableViaWWAN:
                print("蜂窝网络=================")
                break
            case .reachableViaWiFi:
                print("WIFI=================")
                break
            }
        })
        return tools
    }()

    //MARK: - coreMehtod
    func postSoap(_ headerParam: NSDictionary, bodyParam: NSDictionary, bodyMethod:String,success:@escaping (_ responseXML:XMLParser)->(),failed:@escaping ()->()) {
        let dateNow = Date()
        let time = dateNow.timeIntervalSince(appActiveTime!)
        if time > 15 {
            if !NetworkTool.reachable(){
                SVProgressHUD.showError(withStatus: "没有网络")
                failed()
                return
            }
        }
    //  建立soapMessage
        let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n<soap12:Header>\n<Authentication xmlns=\"http://tempuri.org/\">\n\(dictToString(headerParam))</Authentication>\n</soap12:Header>\n<soap12:Body>\n<\(bodyMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(bodyParam))</\(bodyMethod)>\n</soap12:Body>\n</soap12:Envelope>"
        print("-------------------------------")
        print(bodyMethod)
        print(bodyParam)
        print(bodyMethod)
        print("-------------------------------")
        
         //           let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">\n<soap:Header>\n<\(headerMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(headerParam))</\(headerMethod)>\n</soap:Header>\n<soap:Body>\n<\(bodyMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(bodyParam))</\(bodyMethod)>\n</soap:Body>\n</soap:Envelope>"
         
         //        let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n<soap12:Header>\n<Authentication xmlns=\"http://tempuri.org/\">\n<Username>ADgAOAA4YeT+=fue</Username>\n<Password>ADgAOAA4YeT+=fue</Password>\n</Authentication>\n</soap12:Header>\n<soap12:Body>\n<chkUser xmlns=\"http://tempuri.org/\">\n<piUserName>888</piUserName>\n<piPassWord>888</piPassWord>\n</chkUser>\n</soap12:Body>\n</soap12:Envelope>"
        let soapLength:String = String.init(format: "%ld", strlen(soapMessage))
        let theRequest:NSMutableURLRequest! = NSMutableURLRequest(url: URL(string: "http://\((RootIP?.rootIP) ?? "")/\(RootIP?.IPName ?? "")/RF330.asmx")!)
        theRequest.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        //  theRequest.addValue(SOAPAction, forHTTPHeaderField: "SOAPAction")
        theRequest.addValue(soapLength, forHTTPHeaderField: "Content-Length")
        theRequest.httpMethod = "POST"
        theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8)
        let task:URLSessionDataTask = self.dataTask(with: theRequest as URLRequest) { (urlresponse, response, error) in
            LoadingView.dismissLoading()
            guard (error == nil) else{
                failed() //网络请求失败
                return
            }
            do{
                let xml = try AEXMLDocument(xml: response as! Data)
                print(xml.string)
            }
            catch{
                
            }
            let parser = XMLParser(data:response as! Data)
            success(parser)
        }
        LoadingView.showLoading()
        task.resume()
    }
    func postSoap(_ bodyParam: NSDictionary, bodyMethod:String,suffix: String?, success:@escaping (_ data:Data)->(),failed:@escaping ()->()) {
        let dateNow = Date()
        let time = dateNow.timeIntervalSince(appActiveTime!)
        if time > 15 {
            if !NetworkTool.reachable(){
                SVProgressHUD.showError(withStatus: "没有网络")
                failed()
                return
            }
        }
        let headerParam = ["Password":EncryptionTool.encryptString((userInfo?.userPassWord)!),"Username":(userInfo?.userName)!]
        //  建立soapMessage
        let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n<soap12:Header>\n<Authentication xmlns=\"http://tempuri.org/\">\n\(dictToString(headerParam as NSDictionary))</Authentication>\n</soap12:Header>\n<soap12:Body>\n<\(bodyMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(bodyParam))</\(bodyMethod)>\n</soap12:Body>\n</soap12:Envelope>"
        print("-----------------------------------------------------------")
        print(bodyMethod)
        print(bodyParam)
        print(bodyMethod)
        print("-----------------------------------------------------------")
        
        
        //           let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">\n<soap:Header>\n<\(headerMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(headerParam))</\(headerMethod)>\n</soap:Header>\n<soap:Body>\n<\(bodyMethod) xmlns=\"http://tempuri.org/\">\n\(dictToString(bodyParam))</\(bodyMethod)>\n</soap:Body>\n</soap:Envelope>"
        
        //        let soapMessage:String = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n<soap12:Header>\n<Authentication xmlns=\"http://tempuri.org/\">\n<Username>ADgAOAA4YeT+=fue</Username>\n<Password>ADgAOAA4YeT+=fue</Password>\n</Authentication>\n</soap12:Header>\n<soap12:Body>\n<chkUser xmlns=\"http://tempuri.org/\">\n<piUserName>888</piUserName>\n<piPassWord>888</piPassWord>\n</chkUser>\n</soap12:Body>\n</soap12:Envelope>"
        let soapLength:String = String.init(format: "%ld", strlen(soapMessage))
        let theRequest:NSMutableURLRequest! = NSMutableURLRequest(url: URL(string: "http://\((RootIP?.rootIP) ?? "")/\(RootIP?.IPName ?? "")/RF\(suffix ?? "225").asmx")!)
        theRequest.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        //  theRequest.addValue(SOAPAction, forHTTPHeaderField: "SOAPAction")
        theRequest.addValue(soapLength, forHTTPHeaderField: "Content-Length")
        theRequest.httpMethod = "POST"
        theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8)
        let task:URLSessionDataTask = self.dataTask(with: theRequest as URLRequest) { (urlresponse, response, error) in
            LoadingView.dismissLoading()
            guard (error == nil) else{
                failed() //网络请求失败
                return
            }
            let data = response as! Data
            do{
                let xml = try AEXMLDocument(xml: data)
                print(xml.string)
            }
            catch{
                
            }
            
            success(data)
        }
        LoadingView.showLoading()
        task.resume()
    }

    class func reachable() -> (Bool){
        return AFNetworkReachabilityManager.shared().isReachable
    }
    
    //MARK: - privateMethod
    func dictToString(_ dict:NSDictionary) -> String{
        let string = NSMutableString()
        for key in dict.allKeys{
            string.append("<\(key)>\(dict.object(forKey: key)!)</\(key)>\n")
            }
        return string.copy() as! String
    }
    
}
